<script setup lang="ts">
/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
import {
  adGroupList,
  adGroupAdd,
  adGroupUpdate,
  adGroupDel,
  contentAll,
  contentAdd,
  contentEdit,
  contentDel
} from "@/api/content";
import { adGroupQuery, adGroupData } from "@/api/content/types";
import { ElMessage, ElMessageBox } from 'element-plus'
import SingleUpload from "@/components/Upload/SingleUpload.vue";

const queryFormRef = ref(ElForm); // 查询表单
const loading = ref(false);
const ids = ref([]);
const total = ref(0);
const dialog = reactive<DialogOption>({
  visible: false,
});

const queryParams = reactive<adGroupQuery>({
  page: 1,
  ps: 10,
});

const dataList = ref<adGroupData[]>();

// 获取表单
const menuFormRef = ref(ElForm);

// 表单提交数据
const formData = reactive<adGroupData>({
  code: '',
  name: '',
  remark: ''
});

// 表单验证
const rules = reactive({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入唯一标识", trigger: "blur" }],
  remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
});
/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  adGroupList(queryParams)
    .then(({ data }) => {
      dataList.value = data.data;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  handleQuery();
}

// 打开弹窗
const openDialog = (postId?: number | string, data?: any) => {
  dialog.visible = true;
  if (postId) {
    dialog.title = "修改公告";
    Object.assign(formData, data);
  } else {
    dialog.title = "新增公告";
  }
}

/** 关闭弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

// 确认提交
const submitForm = () => {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      if (formData.id) {
        adGroupUpdate(formData).then((res: any) => {
          ElMessage.success(res.msg);
          closeDialog();
          handleQuery();
        })
      } else {
        adGroupAdd(formData).then((res: any) => {
          ElMessage.success(res.msg);
          closeDialog();
          handleQuery();
        })
      }
    }
  })
}

/** 删除菜单 */
function handleDelete(id: number) {
  ElMessageBox.confirm("确认删除该条的数吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    adGroupDel({ ids: [id] }).then(() => {
      ElMessage.success("删除成功");
      handleQuery();
    });
  }).catch(() => ElMessage.info("已取消删除"));
}

/** 重置表单 */
function resetForm() {
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();

  formData.name = '';
  formData.code = '';
  formData.remark = '';
}

// 表单提交数据
const content = reactive<DialogOption>({
  visible: false,
});

// 新增轮播form
const contentForm = reactive<any>({
  group_id: '',
  sort: 0,
  show_status: 1,
  cover: '',
  name: '',
  jump_method: 1,
  jump_url: ''
})

const contenList = ref<any>();

// 打开轮播列表弹窗
const hanldeConten = (data: any) => {
  content.visible = true;
  content.title = data.name;
  contentForm.group_id = data.id;
  getContentList(data.id);
}

const getContentList = (id: number) => {
  contentAll({ group_id: id }).then(res => {
    contenList.value = res.data.lists;
  })
}

// 关闭轮播弹窗
const hanldeCloseDialog = () => {
  dialog.visible = false;
}

// 表单提交数据
const contentAddList = reactive<DialogOption>({
  visible: false,
});

// 打开新增修改轮播图
const openContentDialog = (data?: any) => {
  contentAddList.visible = true;
  if (data) {
    contentAddList.title = "修改轮播";
    Object.assign(contentForm, data);
  } else {
    contentAddList.title = "新增轮播";
  }
}

// 表单验证
const contentRules = reactive({
  sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
  cover: [{ required: true, message: "请选择图片", trigger: "blur" }],
});

// 提交新增轮播
const contentFormRef = ref(ElForm);
const hanldeSubmitForm = () => {
  contentFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      if (contentAddList.title == '修改轮播') {
        contentEdit(contentForm).then((res: any) => {
          ElMessage.success(res.msg);
          hanldeCloseContent();
          getContentList(contentForm.group_id);
        })
      } else {
        contentAdd(contentForm).then((res: any) => {
          ElMessage.success(res.msg);
          hanldeCloseContent();
          getContentList(contentForm.group_id);
        })
      }
    }
  })
}

// 关闭弹窗
const hanldeCloseContent = () => {
  contentAddList.visible = false;
  contentResetForm();
}

/** 重置表单 */
function contentResetForm() {
  contentFormRef.value.resetFields();
  contentFormRef.value.clearValidate();

  contentForm.sort = 0;
  contentForm.show_status = 1;
  contentForm.name = '';
  contentForm.cover = '';
  contentForm.jump_method = 1;
  contentForm.jump_url = ''
}

// 删除轮播
const handleContentDelete = (data: any) => {
  ElMessageBox.confirm("确认删除该条的数吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    contentDel({ ids: [data.id] }).then(() => {
      ElMessage.success("删除成功");
      getContentList(data.group_id);
    });
  }).catch(() => ElMessage.info("已取消删除"));
}

onMounted(() => {
  handleQuery(); // 初始化用户列表数据
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">

      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="唯一标识" prop="s_code">
              <el-input v-model="queryParams.s_code" placeholder="输入唯一标识" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="分组名称" prop="s_name">
              <el-input v-model="queryParams.s_name" placeholder="输入分组名称" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"><i-ep-search />搜索</el-button>
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-card shadow="never">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button v-hasPerm="['adGroup:add']" @click="openDialog()"
                  type="primary"><i-ep-plus />新增分组</el-button>
              </div>
            </div>
          </template>
          <el-table v-hasPerm="['adGroup:pageList']" v-loading="loading" :data="dataList">
            <el-table-column label="id" align="center" prop="id" width="100" />
            <el-table-column label="分组名称" align="center" prop="name" />
            <el-table-column label="唯一标识" align="center" prop="code" />
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column fixed="right" align="center" label="操作" width="220">
              <template #default="scope">
                <el-button v-hasPerm="['ad:all']" type="primary" link size="small"
                  @click.stop="hanldeConten(scope.row)">轮播</el-button>
                <el-button type="primary" link size="small" v-hasPerm="['adGroup:update']"
                  @click.stop="openDialog(scope.row.id, scope.row)">编辑</el-button>
                <el-button v-hasPerm="['adGroup:del']" type="primary" link size="small"
                  @click.stop="handleDelete(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
            v-model:limit="queryParams.ps" @pagination="handleQuery" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加轮播组 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" destroy-on-close append-to-body width="50%"
      @close="closeDialog">
      <el-form ref="menuFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="唯一标识" prop="code">
          <el-input v-model="formData.code" placeholder="请输入唯一标识" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 轮播列表弹窗 -->
    <el-dialog v-model="content.visible" :title="content.title" destroy-on-close append-to-body width="70%"
      @close="hanldeCloseDialog">
      <div class="flex justify-between" style="margin-bottom: 20px;">
        <el-button v-hasPerm="['ad:add']" @click="openContentDialog()" type="primary"><i-ep-plus />新增分组</el-button>
      </div>
      <el-table v-loading="loading" :data="contenList" border height="500px">
        <el-table-column label="id" align="center" prop="id" width="100" />
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column label="图片" align="center" prop="jump_url">
          <template #default="scope">
            <img style="width: 50px;" :src="scope.row.cover" alt="图片" />
          </template>
        </el-table-column>
        <el-table-column label="文字" align="center" prop="name" />
        <el-table-column label="跳转地址" align="center" prop="jump_url">
          <template #default="scope">
            <div v-if="scope.row.jump_method == 1">无</div>
            <div v-else>{{ scope.row.jump_url }}</div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button v-hasPerm="['ad:update']" type="primary" link size="small"
              @click.stop="openContentDialog(scope.row)">编辑</el-button>
            <el-button v-hasPerm="['ad:del']" type="primary" link size="small"
              @click.stop="handleContentDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 新增轮播 -->
    <el-dialog v-model="contentAddList.visible" :title="contentAddList.title" destroy-on-close append-to-body
      width="50%" top="12%" @close="hanldeCloseContent">
      <el-form ref="contentFormRef" :model="contentForm" :rules="contentRules" label-width="100px">
        <el-form-item label="排序" prop="sort">
          <el-input v-model="contentForm.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="唯一标识" prop="show_status">
          <el-radio-group v-model="contentForm.show_status">
            <el-radio :value="1">显示</el-radio>
            <el-radio :value="2">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片" prop="cover">
          <single-upload v-model="contentForm.cover" />
        </el-form-item>
        <el-form-item label="文字" prop="name">
          <el-input v-model="contentForm.name" placeholder="请输入文字" />
        </el-form-item>
        <el-form-item label="跳转状态" prop="jump_method">
          <el-radio-group v-model="contentForm.jump_method">
            <el-radio :value="1">不跳转</el-radio>
            <el-radio :value="2">站内页面</el-radio>
            <el-radio :value="3">站外</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="contentForm.jump_method != 1" label="跳转地址" prop="jump_url">
          <el-input v-model="contentForm.jump_url" placeholder="请输入跳转地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="hanldeSubmitForm">确 定</el-button>
          <el-button @click="hanldeCloseContent">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
